//
//  ByAddAddressVC.m
//  sunsunnewsale
//
//  Created by mc on 2017/7/5.
//  Copyright © 2017年 ZhangZhanbin. All rights reserved.
//

#import "ByAddAddressVC.h"

//Other
#import "ByOtherCityPickerView.h"
#import "ZKBombView.h"

@interface ByAddAddressVC ()<UITableViewDataSource, UITableViewDelegate,ByOtherCityPickerVieDelegate,UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

//@property (nonatomic, strong) ByOtherCityPickerView *cityView;


@property (nonatomic, strong) ZKBombView *picker;


@property (nonatomic, strong) ByOtherCityObject *cityObject;

@end

@implementation ByAddAddressVC

#pragma mark - getter
-(NSMutableArray *)provinceListArray{
    
    if (_provinceListArray == nil) {
        _provinceListArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _provinceListArray;
}

-(NSMutableArray *)cityListArray{
    
    if (_cityListArray == nil) {
        _cityListArray = [[NSMutableArray alloc] initWithCapacity:0];
        
    }
    return _cityListArray;
}

-(NSMutableArray *)areaListArray{
    
    if (_areaListArray == nil) {
        _areaListArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _areaListArray;
}



#pragma mark - 创建数据
-(void)_initCityData{
    
    // 获得全部省的数组
    [self.provinceListArray addObjectsFromArray:[ByCoreAddressSqlite3 getAllProvinceModel]];
    ByCoreProvinceModel *province = [self.provinceListArray firstObject];
    
    // 获得全部城市的数组
    [self.cityListArray addObjectsFromArray:[ByCoreAddressSqlite3 getAllCityModelWithProvinceID:province.provinceID]];
    ByCoreCityModel *city = [self.cityListArray firstObject];
    
    // 获得全部区的数组
    [self.areaListArray addObjectsFromArray:[ByCoreAddressSqlite3 getAllAreaModelWithCityID:city.cityID]];
    
    // 总数据
    self.dataArray =[[NSMutableArray alloc] init];
    [self.dataArray addObject:self.provinceListArray];
    [self.dataArray addObject:self.cityListArray];
    [self.dataArray addObject:self.areaListArray];
}




- (ZKBombView *)picker {
    
    if (!_picker) {
        
        _picker = [[ZKBombView alloc] init];
        _picker.positionMode = ZKBombPositionModeBottom;
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
        view.backgroundColor = [UIColor whiteColor];
        
        view.backgroundColor = [UIColor redColor];
        
      
        
        UIButton *determineBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [view addSubview:determineBtn];
        [determineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(view).offset(0);
            make.bottom.equalTo(view).offset(0);
            make.right.equalTo(view).offset(0);
            make.left.equalTo(view).offset(0);
            make.height.mas_equalTo(@50);
        }];
        
        
        [determineBtn setTitle:@"确定" forState:UIControlStateNormal];
        determineBtn.backgroundColor = BY_THEME_COLOR;
        [determineBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [determineBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
      
        [self _initCityData]; // 从数据库中读取获得城市数据
        
        self.pickerView = [[UIPickerView alloc] init];
        self.pickerView.delegate = self;
        self.pickerView.dataSource = self;
        self.pickerView.backgroundColor = [UIColor whiteColor];
        [view addSubview: self.pickerView];
        
        [self.pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).offset(0);
            make.top.equalTo(view).offset(0);
            make.bottom.equalTo(determineBtn.mas_top).offset(0);
            make.right.equalTo(view).offset(0);
        }];

        _picker.contentView = view;
    }
    return _picker;
    
}


- (void)btnAction:(UIButton *)btn{

    if (self.cityObject && self.cityObject.provinceid && self.cityObject.province) {
        
        
    }else{
        
        ByOtherCityObject *cityObject = [[ByOtherCityObject alloc] init];
        cityObject.province = @"北京市";
        cityObject.provinceid = @"110000";
        cityObject.city = @"市辖区";
        cityObject.cityid = @"110100";
        cityObject.area = @"东城区";
        cityObject.areaid = @"110101";
        cityObject.fullAddress = @"北京市市辖区东城区";
        self.cityObject = cityObject;
    }
    [self.picker remove];
    UITableViewCell * cell2 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    UILabel *addressLabel = [cell2.contentView viewWithTag:100];
    addressLabel.text = self.cityObject.fullAddress;
    
    
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self addLeftBackBarButtonItem];
    self.title = @"添加地址";
    [self initView];
    //[self initCityView];
    
    self.isSetDefault = NO;
    // Do any additional setup after loading the view.
}

- (void)initView{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_NAV) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [footer addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footer).offset(30);
        make.right.equalTo(footer).offset(-30);
        make.bottom.equalTo(footer).offset(0);
        make.height.mas_equalTo(@40);
    }];
    button.backgroundColor = BY_THEME_COLOR;
    [button setTitle:@"保存地址" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 5;
    self.tableView.tableFooterView = footer;
}

- (void)buttonAction:(UIButton *)btn{
    NSLog(@"确定");
    UITableViewCell * cell0 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UITextField *nameTF = [cell0.contentView viewWithTag:100];
    
    UITableViewCell * cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    UITextField *phoneTF = [cell1.contentView viewWithTag:100];
    
    UITableViewCell * cell2 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    UITextField *addressTF = [cell2.contentView viewWithTag:100];
    
  
    if (nameTF.text.length == 0){
        
        [ByCoreToolAlert showOnlyText:@"请输入姓名"];
        return;
        
    }else if (phoneTF.text.length == 0){
        
        [ByCoreToolAlert showOnlyText:@"请输入电话"];
        return;
        
    }else if (!self.cityObject){
        [ByCoreToolAlert showOnlyText:@"请选择地址"];
        return;
        
    }else if (addressTF.text.length == 0){
        
        [ByCoreToolAlert showOnlyText:@"请输入详细地址"];
        return;
        
    }
  
}

- (void)specialHandle{
    if ([_cityObject.province isEqualToString:@"北京市"]) {
        _cityObject.province = @"";
        _cityObject.city = @"北京市";
    }else if ([_cityObject.province isEqualToString:@"天津市"]){
        _cityObject.province = @"";
        _cityObject.city = @"天津市";
    }else if ([_cityObject.province isEqualToString:@"重庆市"]){
        _cityObject.province = @"";
        _cityObject.city = @"重庆市";
    }else if ([_cityObject.province isEqualToString:@"上海市"]){
        _cityObject.province = @"";
        _cityObject.city = @"上海市";
    }else if ([_cityObject.province isEqualToString:@"台湾省"]){
        _cityObject.province = @"";
        _cityObject.city = @"台湾省";
    }else if ([_cityObject.province isEqualToString:@"香港特别行政区"]){
        _cityObject.province = @"";
        _cityObject.city = @"香港特别行政区";
    }else if ([_cityObject.province isEqualToString:@"澳门特别行政区"]){
        _cityObject.province = @"";
        _cityObject.city = @"澳门特别行政区";
    }
    
    
}


#pragma mark - UITableViewDataSource UITableViewDelegate
#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  2;
    
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 4;
    }
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * cellIdentifier = @"UITableViewCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell ==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        UILabel *line = [[UILabel alloc] init];
        [cell addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell).offset(0);
            make.right.equalTo(cell).offset(0);
            make.bottom.equalTo(cell).offset(0);
            make.height.mas_equalTo(@1);
        }];
        line.backgroundColor = BY_LINE_COLOR;
        
    }
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    
    UILabel *titleLabel = [[UILabel alloc] init];
    [cell.contentView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(30);
        make.centerY.equalTo(cell.contentView).offset(0);
        make.size.mas_equalTo(CGSizeMake(120, 20));
    }];
    
    titleLabel.textColor = [UIColor darkGrayColor];
    titleLabel.font = FONT(14);
    if (indexPath.section == 0) {
        NSArray *itemsAry = @[@"收货人",@"联系方式",@"所在地区",@"详细地址"];
        titleLabel.text = itemsAry[indexPath.row];
        if (indexPath.row != 2) {
            UITextField *textField = [[UITextField alloc] init];
            [cell.contentView addSubview:textField];
            [textField mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(titleLabel.mas_right).offset(10);
                make.right.equalTo(cell.contentView).offset(-20);
                make.centerY.equalTo(cell.contentView).offset(0);
                make.height.mas_equalTo(@20);
            }];
            textField.tag = 100 ;
            
            if (indexPath.row == 1) {
                
                textField.keyboardType = UIKeyboardTypeNumberPad;
                
            }
        }else{
            
            UILabel *valueLabel = [[UILabel alloc] init];
            [cell.contentView addSubview:valueLabel];
            [valueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(titleLabel.mas_right).offset(10);
                make.right.equalTo(cell.contentView).offset(-20);
                make.centerY.equalTo(cell.contentView).offset(0);
                make.height.mas_equalTo(@20);
            }];
            valueLabel.textColor = [UIColor darkGrayColor];
            valueLabel.font = FONT(16);
            valueLabel.text = self.cityObject.fullAddress;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            valueLabel.tag = 100;
            
        }
        
        
    }else{
        
        titleLabel.text = @"设为默认地址";
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [cell.contentView addSubview:button];
        button.tag = 1000;
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(cell.contentView).offset(- 25);
            make.centerY.equalTo(cell.contentView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(20, 20));
            
        }];
        [button setBackgroundImage:[UIImage imageNamed:@"morendizhiweixuanzhong"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"morendizhixuanzhong"] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(buttonAction1:) forControlEvents:UIControlEventTouchUpInside];
        
        
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 2) {
        
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        [self.picker show];
        
    }
}

- (void)buttonAction1:(UIButton *)btn{
    btn.selected = !btn.selected;
    if (btn.selected) {
        self.isSetDefault = YES;
    }else{
        self.isSetDefault = NO;
    }
    
    
    
}

#pragma mark --- pickView delegate,datasource
// 列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

// 行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [(NSArray *)[self.dataArray objectAtIndex:component] count];
}

// 每行的标题
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if (component == 0) {
        ByCoreProvinceModel *province = self.provinceListArray[row];
        return province.province;
        
    } else if (component == 1) {
        ByCoreCityModel *city = self.cityListArray[row];
        return city.city;
        
    } else {
        ByCoreAreaModel *area = self.areaListArray[row];
        return area.area;
    }
}


// 选中单元格
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (component == 0) { // 选中第一列（省份）那么第二列和第三列都变为第一行
        
        self.provinceRow = row;
        
        [self getCityData:row]; // 根据选择的省份重新获取城市数组
        [self getAreaData:0]; // 城市数组为当前城市数组中第一个城市的地区数组
        
        self.provinceRow = row;
        self.cityRow = 0;
        self.areaRow = 0;
        
    } else if (component == 1) { // 选中第二列（城市）那么第一列不变，第三列都变为第一行
        
        self.cityRow = row;
        
        [self getAreaData:row]; // 根据选择的城市重新获取地区数组
        
        self.areaRow = 0;
        
        
    } else { // 选中第三列（地区）那么第一列和第二列都变
        
        self.areaRow = row;
    }
    
    [self.pickerView reloadAllComponents];
    
    [self.pickerView selectRow:self.provinceRow inComponent:0 animated:YES];
    [self.pickerView selectRow:self.cityRow inComponent:1 animated:YES];
    [self.pickerView selectRow:self.areaRow inComponent:2 animated:YES];
    
    
    // 每次点击都获取当前的地址
    ByOtherCityObject *cityObject = [self buildCityObject];
    self.cityObject = cityObject;
    // 把当前地址回传到控制器里，设置UI
    NSLog(@"%@ %@ %@ %@ %@ %@ %@", cityObject.province, cityObject.city, cityObject.area, cityObject.provinceid, cityObject.cityid, cityObject.areaid, cityObject.fullAddress);
}

// 创建模型
- (ByOtherCityObject *)buildCityObject{
    
    ByOtherCityObject *object = [[ByOtherCityObject alloc] init];
    // 省
    ByCoreProvinceModel *province = self.provinceListArray[self.provinceRow];
    object.province = province.province;
    object.provinceid =  province.provinceID;
    
    // 市
    if (self.cityListArray.count == 0) { // 某省份下没有市了
        object.city = @"";
        object.cityid  =  @"0";
    } else {
        ByCoreCityModel *city = self.cityListArray[self.cityRow];
        object.city = city.city;
        object.cityid  =  city.cityID;
    }
    
    // 地区
    if (self.areaListArray.count == 0) { // 某市中没有地区了
        object.area = @"";
        object.areaid = @"0";
    } else {
        ByCoreAreaModel *area = self.areaListArray[self.areaRow];
        object.areaid = area.areaID;
        object.area = area.area;
    }
    
    object.fullAddress =[NSString stringWithFormat:@"%@%@%@", object.province, object.city, object.area];
    
    return object;
}


#pragma mark  -- 根据provinceID 读取城市列表
- (void)getCityData:(NSInteger )row{
    
    // 当前省份
    ByCoreProvinceModel *province = self.provinceListArray[row];
    [self.cityListArray removeAllObjects];
    [self.cityListArray setArray:[ByCoreAddressSqlite3 getAllCityModelWithProvinceID:province.provinceID]];
    
    
}
#pragma mark  -- 根据cityID 读取地区列表
-(void)getAreaData:(NSInteger )row{
    
    // 如果没有城市，那么地区也对应没有
    if (self.cityListArray.count == 0) {
        [self.areaListArray removeAllObjects];
        return;
    }
    // 当前城市
    ByCoreCityModel *city = self.cityListArray[row];
    [self.areaListArray removeAllObjects];
    [self.areaListArray setArray:[ByCoreAddressSqlite3 getAllAreaModelWithCityID:city.cityID]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
